package com.cskaoyan.service;

import com.cskaoyan.bean.reverseengineering.MarketPermission;
import com.cskaoyan.bean.reverseengineering.MarketPermissionExample;
import com.cskaoyan.bean.reverseengineering.MarketRole;
import com.cskaoyan.bean.reverseengineering.MarketRoleExample;
import com.cskaoyan.bean.param.BaseParam;
import com.cskaoyan.bean.vo.RoleListVO;
import com.cskaoyan.bean.vo.RoleOptionsListVO;
import com.cskaoyan.bean.vo.RoleOptionsVO;
import com.cskaoyan.bean.vo.permissionvo.ChildrenVO;
import com.cskaoyan.bean.vo.permissionvo.NextChildrenVO;
import com.cskaoyan.bean.vo.permissionvo.RolePermissionsVO;
import com.cskaoyan.bean.vo.permissionvo.SystemPermissionsVO;
import com.cskaoyan.mapper.MarketPermissionManagerMapper;
import com.cskaoyan.mapper.MarketPermissionMapper;
import com.cskaoyan.mapper.MarketRoleMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @description:
 * @author: lxc
 * @date: 2022/5/5 22:39
 */
@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    MarketRoleMapper marketRoleMapper;

    @Autowired
    MarketPermissionManagerMapper marketPermissionManagerMapper;

    @Autowired
    MarketPermissionMapper marketPermissionMapper;

    /**
     * 系统管理，角色管理，显示所有角色
     * @param param
     * @param name
     * @return
     */
    @Override
    public RoleListVO query(BaseParam param, String name) {

        Integer page = param.getPage();//页码
        Integer limit = param.getLimit();//数据量
        String sort = param.getSort();//排序列
        String order = param.getOrder();//desc\asc
        // 分页插件 PageHelper，辅助我们做分页以及分页信息的获得
        PageHelper.startPage(page, limit);
        //执行查询过程中拼接分页信息
        MarketRoleExample marketRoleExample = new MarketRoleExample();
        MarketRoleExample.Criteria criteria = marketRoleExample.createCriteria();

        marketRoleExample.setOrderByClause(sort+" "+order);
        if (name != null && !"".equals(name)){
            criteria.andNameLike("%" + name + "%");
        }
        criteria.andDeletedEqualTo(false);
        List<MarketRole> marketRoles = marketRoleMapper.selectByExample(marketRoleExample);

        //total、pages、list
        //通过PageHelper帮我们来获得一些和分页相关的信息PageInfo
        //使用其有参构造方法 → 形参写来源于数据库的list
        PageInfo<MarketRole> pageInfo = new PageInfo<>(marketRoles);
        long total = pageInfo.getTotal();
        int pages = pageInfo.getPages();
        return RoleListVO.data(total,pages,limit,page,marketRoles);
    }

    /**
     * 系统管理，角色管理，创建角色
     * @param marketRole
     * @return
     */
    @Override
    public MarketRole roleCreate(MarketRole marketRole) {

        marketRole.setAddTime(new Date());
        marketRole.setUpdateTime(new Date());
        marketRoleMapper.insert(marketRole);
        return marketRole;
    }

    /**
     * 系统管理，角色管理，创建角色, 判断角色是否存在
     * @param name
     * @return
     */
    @Override
    public Long selectRole(String name) {

        MarketRoleExample marketRoleExample = new MarketRoleExample();
        MarketRoleExample.Criteria criteria = marketRoleExample.createCriteria();
        criteria.andNameEqualTo(name);
        Long count = marketRoleMapper.countByExample(marketRoleExample);
        return count;
    }

    /**
     * 系统管理，角色管理，管理员页面显示options
     * @return
     */
    @Override
    public RoleOptionsVO selectRoleOptions() {


        int total = (int) marketRoleMapper.countByExample(new MarketRoleExample());
        List<RoleOptionsListVO> roleOptionsListVOs = marketRoleMapper.selectRoleOptions();
        return RoleOptionsVO.data(total,1,total,1,roleOptionsListVOs);
    }

    /**
     * 系统管理，角色管理，删除角色
     * @param marketRole
     * @return
     */
    @Override
    public int roleDelete(MarketRole marketRole) {

        marketRole.setId(marketRole.getId());
        marketRole.setDeleted(true);
        marketRole.setUpdateTime(new Date());

        int affectedRows = marketRoleMapper.updateByPrimaryKeySelective(marketRole);

        return affectedRows;
    }

    /**
     * 系统管理，角色管理，更新角色
     * @param marketRole
     * @return
     */
    @Override
    public int roleUpdate(MarketRole marketRole) {

        int affectedRows = marketRoleMapper.updateByPrimaryKeySelective(marketRole);
        return affectedRows;
    }

    @Override
    public RolePermissionsVO rolePermissions(Integer roleId) {

        // 查询出九个最外层的权限
        List<SystemPermissionsVO> systemPermissions = marketPermissionManagerMapper.selectOutPermission();
        // 查询出九个最外层权限的下一级，即第二级
        for (SystemPermissionsVO systemPermission : systemPermissions) {
            Integer tId = systemPermission.getTId();
            List<NextChildrenVO> nextChildrens = marketPermissionManagerMapper.selectMiddlePermissionsByPid(tId);
            // 查询出第二级的下一级，即第三级
            for (NextChildrenVO nextChildrenVO : nextChildrens) {
                List<ChildrenVO> childrenVO = marketPermissionManagerMapper.selectLastPermissionsByPid(nextChildrenVO.getTId());
                nextChildrenVO.setChildren(childrenVO);
            }
            systemPermission.setChildren(nextChildrens);
        }

        if (roleId == 1){
            String[] assignedPermissions = marketPermissionManagerMapper.selectAllPermissionFromPermissionManageTable();
            return new RolePermissionsVO(assignedPermissions,systemPermissions);
        }
        String[] assignedPermissions = marketPermissionManagerMapper.selectAllIdByRoleId(roleId);

        return new RolePermissionsVO(assignedPermissions,systemPermissions);
    }

    @Override
    public void rolePermissionsUpdate(String[] permissions,Integer roleId) {

        // 先把原先的权限给删掉
        MarketPermission marketPermission = new MarketPermission();
        marketPermission.setDeleted(true);
        MarketPermissionExample marketPermissionExample = new MarketPermissionExample();
        MarketPermissionExample.Criteria criteria = marketPermissionExample.createCriteria();
        criteria.andRoleIdEqualTo(roleId);
        marketPermissionMapper.updateByExampleSelective(marketPermission,marketPermissionExample);

        // 再添加现增的
        for (String permission : permissions) {

            MarketPermission marketPermissionForInsert = new MarketPermission();
            marketPermissionForInsert.setDeleted(false);
            marketPermissionForInsert.setAddTime(new Date());
            marketPermissionForInsert.setUpdateTime(new Date());
            marketPermissionForInsert.setRoleId(roleId);
            marketPermissionForInsert.setPermission(permission);
            marketPermissionMapper.insertSelective(marketPermissionForInsert);

        }
    }

}
